package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 品牌Service
 */
@Service
@Transactional
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> brandPageQuery(Integer page, Integer rows, String key, String sortBy, Boolean desc) {
        //1.封装查询条件
        //注意： QueryWrapper：只能封装查询条件，排序条件（不包含分页的）
        QueryWrapper<Brand> queryWrapper = Wrappers.query();

        //1.1 往QueryWrapper封装查询条件
        if(StringUtils.isNotEmpty(key)){
            /**
             * 参数一：查询的字段名称（不是属性名称）
             * 参数二：查询的参数值
             */
            queryWrapper
                    .like("name",key)
                    .or()
                    .eq("letter",key.toUpperCase());
        }

        //1.2 往QueryWrapper封装排序条件
        if(StringUtils.isNotEmpty(sortBy)){
            if(desc){
                //降序
                queryWrapper.orderByDesc(sortBy);
            }else{
                //升序
                queryWrapper.orderByAsc(sortBy);
            }
        }


        //1.3 IPage: 只封装分页相关的参数
        IPage iPage = new Page(page,rows);


        //2.执行查询
        iPage = brandMapper.selectPage(iPage,queryWrapper);


        //3.处理结果
        /**
         * getTotal(): 获取总记录数
         * getPages(): 获取总页数
         * getRecords(): 当前页列表
         */
        PageResult<Brand> pageResult = new PageResult<Brand>(iPage.getTotal(),iPage.getPages(),iPage.getRecords());

        //4.返回结果
        return pageResult;
    }

    public void saveBrand(Brand brand, List<Long> cids) {
        try {
            //1.保存品牌表
            brandMapper.insert(brand); // 注意：MyBatisPlus在insert方法执行之后自动获取数据库自增id值并赋值给对象，所有对象的ID是有值的！

            //2.保存分类品牌中间表
       /* cids.forEach(cid->{
            saveCategoryAndBrand(brand.getId(),cid);
        });*/

            brandMapper.saveCategoryAndBrand(brand.getId(),cids);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    public Brand findBrandById(Long id) {
        Brand brand = brandMapper.selectById(id);
        if(brand==null){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brand;
    }

    public List<Brand> findBrandsByCid(Long cid) {
        //根据分类id查询品牌列表
        List<Brand> brands = brandMapper.findBrandsByCid(cid);
        if(CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brands;
    }

    public List<Brand> findBrandsByIds(List<Long> ids) {
        List<Brand> brands = brandMapper.selectBatchIds(ids);
        if(CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brands;
    }
}
